package com.example.erp.service.system.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.example.erp.config.CommonConfig;
import com.example.erp.dto.systemDTO.resourceDTO.FileDTO;
import com.example.erp.dto.systemDTO.resourceDTO.ResourceDTO;
import com.example.erp.mapper.permission.UserMapper;
import com.example.erp.pojo.permission.User;
import com.example.erp.service.system.ResourceService;
import com.example.erp.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ResourceServiceA implements ResourceService {
    @Value("${directoryConfig.staticUrl}")
    private String staticUrl;
    @Value("${directoryConfig.staticPath}")
    private String staticPath;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result list(ResourceDTO resourceDTO) {
        long dirSize = FileUtil.size(FileUtil.file(staticPath));
        List<FileDTO> fileList = listQuery(resourceDTO);
        return Result.successMsg(Map.of(
                "rows", fileList,
                "total", fileList.size(),
                "size", dirSize
        ));
    }
    public List<FileDTO> listQuery(ResourceDTO resourceDTO) {
        return CollUtil.filter(getAllFiles(staticPath), entity ->
                // 使用Optional和方法引用简化条件判断
                matchFileName(resourceDTO, entity) &&
                        matchFileType(resourceDTO, entity) &&
                        matchCreateTime(resourceDTO, entity)
        );
    }
    private boolean matchFileName(ResourceDTO resourceDTO, FileDTO entity) {
        return StrUtil.isEmpty(resourceDTO.getFileName()) ||
                StrUtil.contains(entity.getFileName(), resourceDTO.getFileName());
    }
    private boolean matchFileType(ResourceDTO resourceDTO, FileDTO entity) {
        return StrUtil.isEmpty(resourceDTO.getFileType()) ||
                StrUtil.equals(entity.getFileType(), resourceDTO.getFileType());
    }
    private boolean matchCreateTime(ResourceDTO resourceDTO, FileDTO entity) {
        return ArrayUtil.isEmpty(resourceDTO.getCreateTime()) ||
                (entity.getDate().isAfter(resourceDTO.getCreateTime().get(0)) &&
                        entity.getDate().isBefore(resourceDTO.getCreateTime().get(1)));
    }

    @Override
    public Result remove(List<String> fileNames) {
        List<FileDTO> fileList = getAllFiles(staticPath);
        fileList.stream()
                .filter(item1 -> fileNames.contains(item1.getFileName()))
                .map(FileDTO::getPath)
                .forEach(FileUtil::del);
        return Result.successMsg(CommonConfig.msgTYPE.REMOVE.getDescription());
    }

    @Override
    public Result removePic() {
        ResourceDTO resourceDTO = new ResourceDTO("pic");
        List<FileDTO> result = listQuery(resourceDTO);
        int deletedCount  = 0;
        for (FileDTO fileDTO : result) {
            List<User> list = userMapper.getByAvatar(fileDTO.getFileName());
            if(CollUtil.isEmpty(list)){
                try {
                    deletedCount += 1;
                    FileUtil.del(fileDTO.getPath());
                } catch (Exception e) {

                }
            }
        }
        return Result.successMsg(CommonConfig.msgTYPE.REMOVE.getDescription()+",共删除"+deletedCount+"个文件!");
    }

    public List<FileDTO> getAllFiles(String directoryPath) {
        return FileUtil.loopFiles(directoryPath)
                .stream()
                .filter(file -> {
                    String ext = FileUtil.extName(file).toLowerCase();
                    return Arrays.asList("png", "jpg", "jpeg","xls","xlsx").contains(ext);
                })
                .map(file -> {
                    try {
                        String fileName = file.getName();
                        Long millisTimestamp = Long.parseLong(StrUtil.subBefore(fileName, ".", true));
                        LocalDateTime date = DateUtil.toLocalDateTime(Instant.ofEpochMilli(millisTimestamp));

                        String src = file.getAbsolutePath().contains("goods")
                                ? staticUrl + "images/goods/" + fileName
                                : file.getAbsolutePath().contains("user")
                                ? staticUrl + "images/user/" + fileName
                                : "";

                        return new FileDTO(
                                fileName,
                                "pic",
                                date,
                                src,
                                file.getAbsolutePath(),
                                file.length()
                        );
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException(CommonConfig.errorMsg.ERROR.getDescription());
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
